<template>
  <div class="mod-housingEstatus">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <!-- <el-form-item>
        <el-input v-model="dataForm.title" placeholder="活动名称" clearable></el-input>
      </el-form-item> -->
      <el-form-item v-if="superAdmin == 1">
        <el-cascader style="width: 100%;" clearable placeholder="请选择小区" v-model="address" :options="options" :show-all-levels="false" @active-item-change="getNodes" :props="props"></el-cascader>
      </el-form-item>
      <el-form-item >
        <el-button v-if="superAdmin == 1" @click="getDataList()">{{ $t('handle.search') }}</el-button>
        <!--v-if="isAuth('')"是权限的控制-->
        <el-button v-if="isAuth('ic:user:save')" type="primary" @click="addHandle()">{{ $t('handle.add') }}</el-button>
        <!-- <el-button  type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">{{ $t('handle.batchDelete') }}</el-button> -->
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <!-- <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column> -->
      <!-- <el-table-column
        v-if='show'
        prop="id"
        header-align="center"
        align="center"
        width="80"
        label="ID">
      </el-table-column> -->
       <el-table-column
        type="index"
       :label="$t('tabble.No')"
        width="50"
        :index="indexMethod">
      </el-table-column>
      <el-table-column
        v-if="superAdmin == 1"
        :show-overflow-tooltip="true"
        prop="housingEstateName"
        header-align="center"
        align="center"
        :label="$t('adminManage.housing')">
      </el-table-column>
      <el-table-column
        prop="username"
        :show-overflow-tooltip="true"
        header-align="center"
        align="center"
       :label="$t('form.userName')">
      </el-table-column>
      <el-table-column
        prop="nickName"
        :show-overflow-tooltip="true"
        header-align="center"
        align="center"
       :label="$t('form.nickname')">
      </el-table-column>
      <el-table-column
        prop="filterPhone"
        header-align="center"
        align="center"
       :label="$t('form.contactWay')">
      </el-table-column>
      <el-table-column
        prop="deptName"
        header-align="center"
        align="center"
        :label="$t('adminManage.organization')">
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="200"
        :label="$t('handle.handle')">
        <template slot-scope="scope">
          <el-button v-if="isAuth('ic:user:info')" type="text" size="small" @click="infoHandle(scope.row.id)">{{ $t('handle.detail') }}</el-button>
          <el-button   v-if="scope.row.id != currentId && isAuth('ic:user:update')" type="text" size="small" @click="addOrUpdateHandle(scope.row.id)" >{{ $t('handle.update') }}</el-button>
          <el-button  v-if="scope.row.id != currentId && isAuth('ic:user:delete')" type="text" size="small" @click="deleteHandle(scope.row.id,scope.row.username)">{{ $t('handle.delete') }}</el-button>
          <el-button  v-if="scope.row.id != currentId && isAuth('ic:user:resetPwd')" type="text" size="small" @click="resetPwd(scope.row)">重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
  </div>
</template>
<script>
import AddOrUpdate from "./icSysUser-add-or-update";
import { isAuth } from '@/utils'
import {
  getOne,
  getTwo,
  getThree,
  getFour,
  getFive,
  getSix
} from "@/utils/questUtils";
export default {
  data() {
    return {
      currentId: sessionStorage.getItem("userId"),
      superAdmin: sessionStorage.getItem("superAdmin"),
      address: [],
      options: [],
      props: {
        value: "id",
        label: "name",
        children: "children"
      },
      show: false,
      dataForm: {},
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false
    };
  },
  computed: {},
  // 引入的组件
  components: {
    AddOrUpdate
  },
  created() {
    if (this.superAdmin == 1) {
      this.getOne();
    }
  },
  // 一进页面就会执行的方法
  activated() {
      this.getDataList();
  },
  methods: {
    // 一级
    getOne() {
      getOne().then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options = response.data.page;
        }
      });
    },
    // 二级
    getTwo(countryId) {
      getTwo(countryId).then(response => {
        if (response.data.page && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map(item => {
            if (item.id === countryId) {
              item.children = response.data.page;
            }
          });
        }
      });
    },
    getThree(countryId, provinceId) {
      getThree(provinceId).then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((city, id) => {
                city.children = response.data.page;
              });
            }
          });
        }
      });
    },
    getFour(countryId, provinceId, cityId) {
      getFour(cityId).then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((provice, idx) => {
                if (provice.id === provinceId) {
                  provice.children.map((city, ids) => {
                    city.children = response.data.page;
                  });
                }
              });
            }
          });
        }
      });
    },
    getFive(countryId, provinceId, cityId, areaId) {
      getFive(areaId).then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((provice, idx) => {
                if (provice.id === provinceId) {
                  provice.children.map((city, ids) => {
                    if (city.id === cityId) {
                      city.children.map((area, aid) => {
                        area.children = response.data.page;
                      });
                    }
                  });
                }
              });
            }
          });
        }
      });
    },
    getSix(countryId, provinceId, cityId, areaId, communityCodeId) {
      getSix(communityCodeId).then(response => {
        if (response.data && response.data.code === 0) {

          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            // this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((provice, idx) => {
                if (provice.id === provinceId) {
                  provice.children.map((city, ids) => {
                    if (city.id === cityId) {
                      city.children.map((area, aid) => {
                        if (area.id === areaId) {
                          area.children.map((communt, ic) => {
                            communt.children = response.data.page;
                          });
                        }
                      });
                    }
                  });
                }
              });
            }
          });
        }
      });
    },
    getNodes(val) {
      if (val.length === 1) {
        // 获取省
        this.getTwo(val[0]);
      } else if (val.length === 2) {
        // 市
        this.getThree(val[0], val[1]);
      } else if (val.length === 3) {
        // 区
        this.getFour(val[0], val[1], val[2]);
      } else if (val.length === 4) {
        this.getFive(val[0], val[1], val[2], val[3]); //社区
      } else if (val.length === 5) {
        this.getSix(val[0], val[1], val[2], val[3], val[4]); // 小区
      }
      //如果继续添加下级，类似这样继续添加即可
    },
    indexMethod(index) {
      return index + 1;
    },
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      this.$http({
        url: `/dg-ic/ic/sys/user/list`,
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          housingEstateId:
            sessionStorage.getItem("superAdmin") == 1
              ? this.address[this.address.length - 1]
              : sessionStorage.getItem("thiscommunityId") || ""
        })
      }).then(
        ({ data }) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list;
            this.totalPage = data.page.totalCount;
          } else {
            this.dataList = [];
            this.totalPage = 0;
          }
          this.dataListLoading = false;
        },
        error => {
          if (error.response.status === 403) {
            this.$message.error("你没有权限");
          } else {
            this.$message.error("系统错误，请联系管理员");
          }
        }
      );
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    // 新增/修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id, true);
      });
    },
    addHandle(id) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.addinit(id, true);
      });
    },
    // 详情
    infoHandle(id) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id, false);
      });
    },
    resetPwd(row){
      this.$confirm(
        `此操作将重置该用户密码(用户名:` + row.username + `), 是否继续?`,
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(()=>{
        this.$http({
            url: `/dg-ic/ic/sys/user/resetPwd/` + row.username,
            method: "post"
          }).then(
            ({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "重置成功，重置密码为123456",
                  type: "success",
                  duration: 1500
                });
              } else {
                this.$message.error(data.msg);
              }
            },
            error => {
              if (error.response.status === 403) {
                this.$message.error("你没有重置权限");
              } else {
                this.$message.error("系统错误，请联系管理员");
              }
            }
          );
      })
    },
    // 删除
    deleteHandle(id,username) {
      // 遍历拿到选择的id
      var ids = id
        ? [id]
        : this.dataListSelections.map(item => {
            return item.id;
          });
      var usernames = username
        ? [username]
        : this.dataListSelections.map(item => {
            return item.username;
          });
      this.$confirm(
        `确定对[用户名=${usernames.join(",")}]进行[${id ? "删除" : "批量删除"}]操作?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          this.$http({
            url: `/dg-ic/ic/sys/user/delete`,
            method: "delete",
            data: this.$http.adornData(ids, false)
          }).then(
            ({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "删除成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.getDataList();
                  }
                });
              } else {
                this.$message.error(data.msg);
              }
            },
            error => {
              if (error.response.status === 403) {
                this.$message.error("你没有删除权限");
              } else {
                this.$message.error("系统错误，请联系管理员");
              }
            }
          );
        })
        .catch(() => {});
    }
  }
};
</script>

